//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////
//
//	Main Window
//
#include <wx/wx.h>
#include <stdio.h>
#include <wx/aboutdlg.h> 
#include <wx/statusbr.h>
#include <wx/file.h>
#include <wx/sstream.h>
#include <wx/protocol/http.h>
#include "conectwizard.h"
#include "mainwnd.h"
#include "rtevents.h"
#include "statuspanel.h"
#include "propertydlg.h"
#include "taskbaricon.h"
#include "connectionstab.h"
#include "rcmdapp.h"
#include "syslogtab.h"
#include "stattab.h"
#include "userstab.h"
#include "ipsettingstab.h"
#include "portforwardtab.h"
#include "updatedlg.h"
#include "adsltab.h"
#include "advancedoptdlg.h"
#include "isptab.h"
#include "wirelesstab.h"
#include "perfomancetab.h"
#include "reportwindow.h"
#include "routercaps.h"
#include "pingtab.h"

enum cIDS
{
	ID_TOOLBAR=1,
	ID_CON_WIZARD=wxID_HIGHEST+1,
	ID_TAB_CTRL,
	ID_CON_OPTIONS,
	ID_VIEW_UPD_SPEED_HIGH,
	ID_VIEW_UPD_SPEED_NORMAL,
	ID_VIEW_UPD_SPEED_LOW,
	ID_VIEW_LOG,
	ID_CONFIG,
	ID_TOOLS_RTRESTR,
	ID_VIEW_HELP_PANEL,
	ID_EVAL_PROGRESS,
	ID_HELP_UPGRADE,
	ID_HELP_MANUAL,
	ID_TOOLS_P2P_OPT,
	ID_TOOLS_WWW_OPT,
	ID_HELP_TRANSLATE,
	ID_TOOLS_CUSTOM_OPT,
	ID_VIEW_ADVANCED,
	ID_HELP_DONATION,
	ID_HELP_COMPREPORT,
	ID_VIEW_UPD_PERIOD_60,
	ID_VIEW_UPD_PERIOD_300,
	ID_VIEW_UPD_PERIOD_600,
	ID_VIEW_UPD_PERIOD_1800,
	ID_VIEW_UPD_PERIOD_1H,
	ID_VIEW_UPD_PERIOD_4H,
	ID_VIEW_UPD_PERIOD_8H,
	ID_VIEW_UPD_PERIOD_12H,
	ID_VIEW_UPD_PERIOD_16H,
	ID_VIEW_UPD_PERIOD_20H,
	ID_VIEW_UPD_PERIOD_24H
};

typedef struct tagTMPERIOD
{
	unsigned int iID;
	unsigned int iVAL;
}TMPERIOD;

TMPERIOD gPerTable[] = {
	{ ID_VIEW_UPD_PERIOD_60,	60		},
	{ ID_VIEW_UPD_PERIOD_300,	5*60	},
	{ ID_VIEW_UPD_PERIOD_600,	10*60	},
	{ ID_VIEW_UPD_PERIOD_1800,	30*60	},
	{ ID_VIEW_UPD_PERIOD_1H,	60*60	},
	{ ID_VIEW_UPD_PERIOD_4H,	4*60*60	},
	{ ID_VIEW_UPD_PERIOD_8H,	8*60*60	},
	{ ID_VIEW_UPD_PERIOD_12H,	12*60*60},
	{ ID_VIEW_UPD_PERIOD_16H,	16*60*60},
	{ ID_VIEW_UPD_PERIOD_20H,	20*60*60},
	{ ID_VIEW_UPD_PERIOD_24H,	24*60*60},
};

BEGIN_EVENT_TABLE(CMainWnd, wxFrame)
	EVT_ON_THREAD_EXIT(wxID_ANY, CMainWnd::OnProcessThreadExit)
	EVT_ON_ROUTER_THREAD(wxID_ANY, CMainWnd::OnProcessRouterData)
	EVT_MENU(wxID_EXIT, CMainWnd::OnQuit)
	EVT_MENU(ID_CON_WIZARD, CMainWnd::OnConWizard)
	EVT_MENU(ID_CON_OPTIONS, CMainWnd::OnOptions)
	EVT_MENU(wxID_ABOUT, CMainWnd::OnAbout )
	EVT_MENU(wxID_REFRESH, CMainWnd::OnRefresh )
	EVT_MENU_RANGE(ID_VIEW_UPD_SPEED_HIGH, ID_VIEW_UPD_SPEED_LOW, CMainWnd::OnUpdateSpeed )
	EVT_ICONIZE( CMainWnd::OnIconize )
	EVT_UPDATE_UI_RANGE(ID_VIEW_UPD_SPEED_HIGH, ID_VIEW_UPD_SPEED_LOW, CMainWnd::OnUpdateSpeedUpdateUI)
	EVT_MENU(ID_VIEW_LOG, CMainWnd::OnViewLOG)
	EVT_MENU(ID_CONFIG, CMainWnd::OnConfig)
	EVT_MENU(wxID_REFRESH, CMainWnd::OnRefreshOne)
	EVT_UPDATE_UI(ID_VIEW_LOG, CMainWnd::OnViewLOGUpdateUI)
	EVT_AUINOTEBOOK_PAGE_CHANGED(ID_TAB_CTRL, CMainWnd::OnTabPageChanged)
	EVT_ON_SYSLOGMSG(wxID_ANY, CMainWnd::OnNewLogMsg)
	EVT_MENU(wxID_SAVE, CMainWnd::OnSave)
	EVT_UPDATE_UI(wxID_SAVE, CMainWnd::OnSaveUI)
	EVT_MENU(wxID_CLEAR, CMainWnd::OnClear)
	EVT_UPDATE_UI(wxID_CLEAR, CMainWnd::OnClearUI)
	EVT_MENU(ID_TOOLS_RTRESTR, CMainWnd::OnRestartRT)
	EVT_UPDATE_UI(ID_TOOLS_RTRESTR, CMainWnd::OnRestartRTUI)
	EVT_MENU(ID_VIEW_HELP_PANEL, CMainWnd::OnHelpPanel)
	EVT_UPDATE_UI(ID_VIEW_HELP_PANEL, CMainWnd::OnHelpPanelUI)
	EVT_AUI_PANE_CLOSE(CMainWnd::OnPanelClose)
	EVT_MENU(ID_HELP_UPGRADE, CMainWnd::OnUpdateCheck)
	EVT_MENU(ID_HELP_MANUAL, CMainWnd::OnHelp)
	EVT_MENU(ID_HELP_TRANSLATE, CMainWnd::OnHelpTranslate)
	EVT_HELP_RANGE(0, wxID_ANY, CMainWnd::OnHelpPressed) /*doesn't work*/
	EVT_MENU_RANGE(ID_TOOLS_P2P_OPT, ID_TOOLS_CUSTOM_OPT, CMainWnd::OnOptimizationSelector )
	EVT_UPDATE_UI_RANGE(ID_TOOLS_P2P_OPT, ID_TOOLS_CUSTOM_OPT, CMainWnd::OnOptimizationSelectorUI)

	EVT_UPDATE_UI(ID_VIEW_ADVANCED, CMainWnd::OnAdvancedUpdateUI)
	EVT_MENU(ID_VIEW_ADVANCED, CMainWnd::OnAdvanced)

	EVT_MENU(ID_HELP_DONATION, CMainWnd::OnDonation)

	EVT_MENU(ID_HELP_COMPREPORT, CMainWnd::OnCompatibReport)
	EVT_UPDATE_UI(ID_HELP_COMPREPORT, CMainWnd::OnCompatibReportUI)

	EVT_MENU_RANGE(ID_VIEW_UPD_PERIOD_60, ID_VIEW_UPD_PERIOD_24H, CMainWnd::OnTimeSelector )
	EVT_UPDATE_UI_RANGE(ID_VIEW_UPD_PERIOD_60, ID_VIEW_UPD_PERIOD_24H, CMainWnd::OnTimeSelectorUI)
	
END_EVENT_TABLE()

CMainWnd::CMainWnd(CConfigData& config, const wxString& title, const wxPoint& pos, const wxSize& size):
	wxFrame((wxFrame *)NULL, -1, title, pos, size),m_config(config), m_guilogic(*this), m_propStorage(m_config, m_guilogic),
	m_pSysLog(NULL), m_pBook(NULL), m_strTitle(title), m_pHelpPanel(NULL), m_bInside(false), m_pPerfomance(NULL),
	m_pConnections(NULL), m_pBandwidth(NULL), m_pAccess(NULL), m_pPortForward(NULL), m_pIPSettings(NULL), m_pADSL(NULL), m_pWireless(NULL),
	m_pPing(NULL)
{
	wxInitAllImageHandlers();

	//Icon
	wxIcon icnApp;

	if ( icnApp.LoadFile( wxGetApp().GetImageDir()+ wxT("app_icon.ico"),   wxBITMAP_TYPE_ICO ) )
	{
		SetIcon( icnApp );
	}
	else
	if ( icnApp.LoadFile(wxGetApp().GetImageDir()+wxT("app_icon.png"),   wxBITMAP_TYPE_PNG ) )
	{
		SetIcon( icnApp );
	}

	m_mgr.SetManagedWindow(this);
	
	m_pBook = new wxAuiNotebook(this, ID_TAB_CTRL, wxDefaultPosition, wxDefaultSize, wxAUI_NB_DEFAULT_STYLE&(~wxAUI_NB_CLOSE_ON_ACTIVE_TAB));

	if ( m_pBook )
	{
		m_mgr.AddPane(m_pBook, wxCENTER);
	}

	m_pHelpPanel = new CHelpPanel(this);

	LoadSettings();

	if ( m_pHelpPanel )
	{
		if ( m_propStorage.GetShowHelpPanel() )
		{
			m_mgr.AddPane(m_pHelpPanel, wxRIGHT);
		}
		else
			m_pHelpPanel->Show(false);
	}

	CreateStatusBar(4, wxST_SIZEGRIP|wxFULL_REPAINT_ON_RESIZE|wxSTB_ELLIPSIZE_END);
	
	InitMenu();
	
	InitToolBar();
	
	m_mgr.Update();
	
	Center();
}

void CMainWnd::StartUp()
{
	try
	{
		InitWorkArea();
		m_guilogic.Init();

		InitRouterConnection();

		if ( m_propStorage.GetUpdCheck() )
			DoUpdateCheck(true);
	}
	catch(...)
	{
	}
}

CMainWnd::~CMainWnd()
{
	m_guilogic.CleanUp();
	m_guilogic.DestroyLinkToRouter();

	m_mgr.UnInit();

	while( m_bInside)
	{
		wxGetApp().Dispatch();
	}
}

void CMainWnd::LoadSettings()
{
	try
	{
		m_propStorage.Load();

		m_guilogic.SetUpdateSpeed( m_propStorage.GetUpdateSpeed() );

	}catch(...)
	{
		
	}
}


void CMainWnd::InitMenu()
{
	//File
	wxMenu *fileMenu = new wxMenu;
	fileMenu->Append(wxID_SAVE, _("Save"), _("Save") );
	fileMenu->Append(wxID_EXIT, _("E&xit"), _("Quit") );

	//View
	wxMenu *viewMenu = new wxMenu;
	viewMenu->Append(wxID_REFRESH, _("Refresh Now"), _("Refresh Now") );
	wxMenu *viewUpdateSpeedMenu = new wxMenu;
	viewUpdateSpeedMenu->AppendRadioItem(ID_VIEW_UPD_SPEED_HIGH,_("High"));
	viewUpdateSpeedMenu->AppendRadioItem(ID_VIEW_UPD_SPEED_NORMAL,_("Normal"));
	viewUpdateSpeedMenu->AppendRadioItem(ID_VIEW_UPD_SPEED_LOW,_("Slow"));
	viewMenu->AppendSubMenu(viewUpdateSpeedMenu, _("Update Speed"), _("Update Speed"));
	
	//Time
	wxMenu *viewGraphIntervalMenu = new wxMenu;

	wxString strM(_("minute"));
	wxString strMs(_("minutes"));
	wxString strH(_("hour"));
	wxString strHs(_("hours"));

	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_60, wxString(wxT("1 "))+strM );	//60
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_300, wxString(wxT("5 "))+strMs );	//(5*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_600, wxString(wxT("10 "))+strMs );//(10*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_1800, wxString(wxT("30 "))+strMs );//(30*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_1H, wxString(wxT("1 "))+strH );//(60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_4H, wxString(wxT("4 "))+strHs );//(4*60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_8H, wxString(wxT("8 "))+strHs );//(8*60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_12H, wxString(wxT("12 "))+strHs );//(12*60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_16H, wxString(wxT("16 "))+strHs );//(16*60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_20H, wxString(wxT("20 "))+strHs );//(20*60*60)
	viewGraphIntervalMenu->AppendRadioItem(ID_VIEW_UPD_PERIOD_24H, wxString(wxT("24 "))+strHs );//(20*60*60)
	viewMenu->AppendSubMenu(viewGraphIntervalMenu, _("Show for period"), _("Show for period"));

	viewMenu->Append(wxID_CLEAR,			_("Clear"),			_("Clear") );
	viewMenu->AppendSeparator();
	viewMenu->Append(ID_VIEW_LOG,			_("Log"),			_("Application Log"));
	viewMenu->Append( ID_VIEW_HELP_PANEL,	_("Help Panel"),	_("View Help Panel"));


	//Tools
	wxMenu *toolsMenu = new wxMenu;
	toolsMenu->Append(ID_TOOLS_RTRESTR, _("&Restart Router"), _("Restart router"));
	toolsMenu->Append(ID_CON_WIZARD,	_("&Connection Wizard"), _("Connection Wizard"));
	toolsMenu->Append(ID_CON_OPTIONS,	_("&Options"), _("Options"));

	//Help
	wxMenu *helpMenu = new wxMenu;
	helpMenu->Append(ID_HELP_MANUAL,	_("Online Manual"),		_("Online Manual"));
	helpMenu->Append(ID_HELP_TRANSLATE,	_("How to translate"),	_("Translate Router Commander to your languge"));
	
	helpMenu->Append(ID_HELP_DONATION,	_("Please Donate!"), _("Say thank you to developer"));
	helpMenu->Append(ID_HELP_COMPREPORT,_("Add to Compatible Router List"), _("Add to Compatible Router List"));

	
	helpMenu->Append(ID_HELP_UPGRADE,	_("Check for Updates"), _("Check for Updates"));
	helpMenu->Append(wxID_ABOUT,		_("&About"),			_("About"));
	

	wxMenuBar* menuBar = new wxMenuBar;
	menuBar->Append(fileMenu, _("&File"));
	menuBar->Append(viewMenu, _("&View"));
	menuBar->Append(toolsMenu, _("&Tools"));
	menuBar->Append(helpMenu, _("&Help"));

	// Associate the menu bar with the frame
	SetMenuBar(menuBar);
}

void CMainWnd::InitToolBar()
{
	wxToolBar* pTB = CreateToolBar(wxNO_BORDER|wxHORIZONTAL|wxTB_FLAT|wxTB_TEXT, ID_TOOLBAR);

	wxBitmap bm;
	 
	if ( pTB )
	{
		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_save.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(wxID_SAVE, _("Save"), bm, _("Save") );
		}

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_refresh.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(wxID_REFRESH, _("Refresh"), bm, _("Refresh"));
		}

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_clear.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(wxID_CLEAR, _("Clear"), bm, _("Clear"));
		}

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_advanced.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(ID_VIEW_ADVANCED, _("Advanced"), bm, _("Advanced"), wxITEM_CHECK);
		}

		pTB->AddSeparator();

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_p2p.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(ID_TOOLS_P2P_OPT, _("Peer-to-Peer"), bm, _("Peer-to-Peer optimization"), wxITEM_RADIO );
		}

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_web.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(ID_TOOLS_WWW_OPT, _("WWW/FTP"), bm, _("WWW/FTP, persistent connect optimization"), wxITEM_RADIO );
		}

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_custom.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(ID_TOOLS_CUSTOM_OPT, _("Custom"), bm, _("Custom optimization"), wxITEM_RADIO );
		}

		pTB->AddSeparator();

		if ( bm.LoadFile(wxGetApp().GetImageDir()+wxT("toolbar_restart.png"), wxBITMAP_TYPE_PNG) )
		{
			pTB->AddTool(ID_TOOLS_RTRESTR, _("Restart router"), bm,  _("Restart router"));
		}

		pTB->Realize();
	}
}

//Calls every time router shell, modem or Wireless caps received
void CMainWnd::OnRouterConnected()
{
	if ( m_pBook )
	{
		//Perfomance
		if ( !m_pPerfomance )
		{
			if ( CRouterCaps::GetIntstance().HasNATUsageInfo() ||
				CRouterCaps::GetIntstance().HasMEMUsageInfo() ||
				CRouterCaps::GetIntstance().HasRTUsageInfo()  ||
				CRouterCaps::GetIntstance().HasCPUUsageInfo() )
			{
				
				m_pPerfomance = CreatePerfomanceTab();
				m_pBook->InsertPage(0, m_pPerfomance, _("Perfomance"), true);
			}
		}

		//Connections
		if ( !m_pConnections )
		{
			if ( CRouterCaps::GetIntstance().HasConnectionsList() )
			{
				m_pConnections = CreateConnectionsTab();
				m_pBook->InsertPage( 1, m_pConnections, _("Connections"), false);
			}
		}

		//Bandwidth
		if (!m_pBandwidth)
		{
			if ( CRouterCaps::GetIntstance().HasBandwidth() )
			{
				m_pBandwidth = CreateStatTab();
				m_pBook->InsertPage( 2,  m_pBandwidth, _("Bandwidth"), false);
			}
		}

		//Access
		if (!m_pAccess)
		{
			if ( CRouterCaps::GetIntstance().HasMACFilter() )
			{
				m_pAccess = CreateUsersTab();
				m_pBook->InsertPage( 3,  m_pAccess, _("Access"), false);
			}
		}

		//Port Forward
		if (!m_pPortForward)
		{
			if ( CRouterCaps::GetIntstance().HasPortForward() )
			{
				m_pPortForward = CreatePortForwardTab();
				m_pBook->InsertPage(4, m_pPortForward, _("Port Forwarding"), false);
			}
		}

		//IP Settings
		if (!m_pIPSettings)
		{
			m_pIPSettings = CreateIPSettingsTab();
			m_pBook->InsertPage(5, m_pIPSettings, _("IP Settings"), false);
		}

		//ADSL settings
		if (!m_pADSL)
		{
			if ( CRouterCaps::GetIntstance().HasBuitInModem() )
			{
				m_pADSL = CreateADSLTab();
				m_pBook->InsertPage(6, m_pADSL, _("ADSL"), false);
			}
		}

		//Wireless
		if (!m_pWireless)
		{
			if ( CRouterCaps::GetIntstance().HasBuitInWireless() )
			{
				m_pWireless = CreateWirelessTab();
				m_pBook->AddPage( m_pWireless, _("Wireless"), false);
			}
		}
	}
}

//Add router independent GUI initialization here
void CMainWnd::InitWorkArea()
{
	if ( m_pBook )
	{
		m_pSysLog = CreateSysLogTab();
		m_pBook->AddPage( m_pSysLog, _("SysLog"), true);

		m_pPing = CreatePingTab();
		m_pBook->AddPage( m_pPing, _("Ping"), true);
	}
}

void CMainWnd::RemoveTab(cCmdCode cmd)
{
	if (!m_pBook) return;

	GUIBIND bindOut;
	if ( GetLogic().GetBind( bindOut, cmd ) )
	{
		for ( size_t i=0;i<m_pBook->GetPageCount();++i)
		{
			try
			{
				wxWindow* wnd = m_pBook->GetPage(i);
				IGUIBind* pBind = dynamic_cast<IGUIBind*>(wnd);

				if ( bindOut.GetBinding() == pBind )
				{
					wnd->Show( false );
					m_pBook->RemovePage( i );
					break;
				}
			}
			catch (...)
			{
			}
		}
	}
}

wxWindow* CMainWnd::CreatePerfomanceTab()
{
	CPerfomanceTab* pTab = new CPerfomanceTab(m_pBook, m_guilogic, m_propStorage);

	GUIBIND bind;

	bind.bEnabled	= false;
	bind.codeMaxVal = cInternalCmdGetPerfomanceTab;
	bind.codeVal    = cInternalCmdGetPerfomanceTab;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateConnectionsTab()
{
	CConnectionsTab* pTab = new CConnectionsTab(m_pBook);

	GUIBIND bind;

	bind.tUpdateDelay = 30;
	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdConntrTableEntries;
	bind.codeVal    = cCmdConntrTableEntries;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateSysLogTab()
{
	CSysLogTab* pTab = new CSysLogTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= false;
	bind.codeMaxVal = cCmdSysLogMessage;
	bind.codeVal    = cCmdSysLogMessage;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateStatTab()
{
	CStatTab* pTab = new CStatTab(m_pBook);

	GUIBIND bind;
	/*
	bind.bEnabled	= false;
	bind.codeMaxVal = cCmdWirelessStat;
	bind.codeVal    = cCmdWirelessStat;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );
	*/

	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdInterfaceStat;
	bind.codeVal    = cCmdInterfaceStat;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	bind.bEnabled	= true;
	bind.tUpdateDelay = 60;
	bind.codeMaxVal = cCmdPing;
	bind.codeVal    = cCmdPing;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );
	
	return pTab;
}

wxWindow* CMainWnd::CreateUsersTab()
{
	CUsersTab* pTab = new CUsersTab(m_pBook);

	GUIBIND bind;

	/*
	//Must be requested first
	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdGetRoutingTable;
	bind.codeVal    = cCmdGetRoutingTable;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );
	*/

	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdARPTable;
	bind.codeVal    = cCmdARPTable;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdMACBlockExecuted;
	bind.codeVal    = cCmdMACBlockExecuted;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateIPSettingsTab()
{
	CIPSettingsTab* pTab = new CIPSettingsTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= true;
	bind.bOneShort  = true;
	bind.codeMaxVal = cCmdGetIPConfig;
	bind.codeVal    = cCmdGetIPConfig;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);

	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreatePortForwardTab()
{
	CPortForwardTab* pTab = new CPortForwardTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= false;
	bind.bOneShort  = true;
	bind.codeMaxVal = cCmdPFTableUpdated;
	bind.codeVal    = cCmdPFTableUpdated;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);

	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateADSLTab()
{
	CADSLTab* pTab = new CADSLTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdGetModemStats;
	bind.codeVal    = cCmdGetModemStats;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateWirelessTab()
{
	CWirelessTab* pTab = new CWirelessTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= false;
	bind.codeMaxVal = cCmdGetWirelessStats;
	bind.codeVal    = cCmdGetWirelessStats;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreateISPTab()
{
	CISPTab* pTab = new CISPTab(m_pBook);

	GUIBIND bind;

	bind.bEnabled	= true;
	bind.codeMaxVal = cCmdPing;
	bind.codeVal    = cCmdPing;
	bind.SetBinding( pTab );
	bind.pStorage	= NULL;
	bind.plType		= cPTNone;
	bind.SetMaxVal(1);
	m_guilogic.AddBind( bind );

	return pTab;
}

wxWindow* CMainWnd::CreatePingTab()
{
	CPingTab* pTab = new CPingTab(m_pBook);

	return pTab;
}

void CMainWnd::InitRouterConnection()
{
	try
	{
		CONPARAMS params;
		CheckConnectionParams(params);
		m_guilogic.StartLinkToRouter(params);
	}
	catch(...)
	{
		wxMessageBox(_("Connect to router failed!"), _("Error"),
		                         wxICON_WARNING | wxOK, this);
	}
}

void CMainWnd::CheckConnectionParams(CONPARAMS& params)
{
	try
	{
		params.strUsr   = m_config.GetUser();
		params.strPassw = m_config.GetPassword();
		params.strIP 	= m_config.GetIP();
		params.wPort 	= m_config.GetPort();
		params.cProto	= m_config.GetProtocol();

		params.bEnableSSHKey = m_config.GetUseSSHKeys();
		params.strPublickey = m_config.GetPubKey();
		params.strPrivkey = m_config.GetPrivKey();
		params.strPassphrase = m_config.GetPassPhrase();

		params.strLoginPrompt = m_config.GetLoginPromptString();
		params.strShell = m_config.GetShellString();

		params.strHTTP = m_config.GetHTTPString();
		params.bHTTPEnable = m_config.GetHTTPEnable();
	}
	catch(...)
	{
		ShowConnectionWizard(params);
	}
}

void CMainWnd::ShowConnectionWizard()
{
	try
	{
		CONPARAMS params;
		
		try
		{
			params.strUsr   = m_config.GetUser();
			params.strPassw = m_config.GetPassword();
			params.strIP 	= m_config.GetIP();
			params.wPort 	= m_config.GetPort();
			params.cProto	= m_config.GetProtocol();

			params.bEnableSSHKey = m_config.GetUseSSHKeys();
			params.strPublickey = m_config.GetPubKey();
			params.strPrivkey = m_config.GetPrivKey();
			params.strPassphrase = m_config.GetPassPhrase();

			
			params.strLoginPrompt = m_config.GetLoginPromptString();
			params.strShell = m_config.GetShellString();

			params.strHTTP = m_config.GetHTTPString();
			params.bHTTPEnable = m_config.GetHTTPEnable();

		}
		catch(...)	{ }
	
		m_guilogic.SetAutoConnect(false);
		m_guilogic.DestroyLinkToRouter();
		ShowConnectionWizard(params);
		m_guilogic.SetAutoConnect(true);
		m_guilogic.StartLinkToRouter(params);
	}
	catch(...)
	{
		m_guilogic.SetAutoConnect(true);
	}
}

//First time only
void CMainWnd::ShowConnectionWizard(CONPARAMS& params)
{
	CConectWizard wzrd(this);
	
	wzrd.GetConParams(params);
	
	//Save params
	m_config.SetUser(params.strUsr);
	m_config.SetPassword(params.strPassw);
	m_config.SetIP(params.strIP);
	m_config.SetPort(params.wPort);
	m_config.SetProtocol(params.cProto);

	m_config.SetUseSSHKeys(params.bEnableSSHKey);
	m_config.SetPubKey(params.strPublickey);
	m_config.SetPrivKey(params.strPrivkey);
	m_config.SetPassPhrase(params.strPassphrase);

	m_config.SetLoginPromptString( params.strLoginPrompt  );
	m_config.SetShellString( params.strShell );

	m_config.SetHTTPString(params.strHTTP);
	m_config.SetHTTPEnable(params.bHTTPEnable);

}

void CMainWnd::ShowConfig(PANELTYPE pl)
{
	bool bRestart(false);
	
	try
	{
		long lUdpPort = m_propStorage.GetSysLogUDPPort();

		CPropertyDlg dlg(m_propStorage);
	
		if ( dlg.Create(pl) )
		{
			if ( wxID_OK==dlg.ShowModal() )
			{
				dlg.Save(bRestart);
				
				m_propStorage.Save();
				
	
				if ( bRestart )
				{
					Close();
					
					wxGetApp().Restart();
				}
				else
				{
					if ( lUdpPort!=m_propStorage.GetSysLogUDPPort() )
					{
						m_guilogic.ReInitSysLogSrv();
					}

					m_guilogic.DoStartUpAction();

					
				}
			}
		}
	}catch(...)
	{
		
	}
}


void CMainWnd::Refresh()
{
	m_guilogic.Refresh();
}

void CMainWnd::OnPopUpMenu( const wxPoint& pt, wxWindow* pParent )
{
	GUIBIND bind;
	
	m_plCurType = cPTNone;
	
	wxPoint ptCl = ScreenToClient(pt);
	
	if ( m_guilogic.GetBind( bind, ((CStatusPanel*)pParent)->GetBind() ) )
	{
		m_plCurType = bind.plType;
		
		wxMenu* pMenu = new wxMenu();
		pMenu->Append(wxID_REFRESH,  _("Refresh"), _("Refresh Now") );
		pMenu->Append(ID_CONFIG,  _("Configure"), _("Configure") );
		DoPopupMenu(pMenu, ptCl.x, ptCl.y );
	}
}


//////////////////////////////////////////////////////////////////////////////////////////
//Gui
void CMainWnd::OnTabPageChanged(class wxAuiNotebookEvent& ev)
{
	int nTabIDX = ev.GetSelection();

	wxWindow* pWnd = m_pBook->GetPage(nTabIDX);

	if ( pWnd)
	{
		ITabedPageUI* pTab = dynamic_cast<ITabedPageUI*>(pWnd);

		if ( pTab )
		{
			cTabPageID nTabID = pTab->GetTabID();

			if ( cTabIDConnections==ev.GetSelection() )
			{
				m_guilogic.SetCMDUpdateDelay(cCmdConntrTableEntries, 0);
				m_guilogic.Refresh();
			}
			else
			{
				m_guilogic.SetCMDUpdateDelay(cCmdConntrTableEntries, 30);
			}
			
			if ( cTabIDBandwidth==ev.GetSelection() )
			{
				//m_guilogic.EnableCmd(cCmdWirelessStat);
				//m_guilogic.EnableCmd(cCmdInterfaceStat);
				//m_guilogic.Refresh();
			}
			else
			{
				//m_guilogic.EnableCmd(cCmdWirelessStat,	false);
				//m_guilogic.EnableCmd(cCmdInterfaceStat,	false);
			}

			if ( cTabIDReport==ev.GetSelection() )
			{
				m_guilogic.EnableCmd(cCmdGetIPConfig);
			}

			if (m_pHelpPanel)
			{
				m_pHelpPanel->ShowHelp( (cTabPageID)nTabID );
			}
		}
	}
}

void CMainWnd::UpdateHelpPage()
{
	if ( m_pHelpPanel && m_pBook )
	{
		int nTabIDX =m_pBook->GetSelection();

		wxWindow* pWnd = m_pBook->GetPage(nTabIDX);

		if ( pWnd)
		{
			ITabedPageUI* pTab = dynamic_cast<ITabedPageUI*>(pWnd);

			if ( pTab )
			{
				cTabPageID nTabID = pTab->GetTabID();

				m_pHelpPanel->ShowHelp( nTabID );
			}
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
//Menu
void CMainWnd::OnSave(wxCommandEvent& event)
{
	try
	{
		wxFileDialog dlg(this, wxFileSelectorPromptStr,  wxEmptyString,  wxEmptyString, wxFileSelectorDefaultWildcardStr, wxFD_SAVE|wxFD_OVERWRITE_PROMPT);

		if ( wxID_OK ==dlg.ShowModal() )
		{
			int page_idx = m_pBook->GetSelection();
			if (wxNOT_FOUND==page_idx) return;

			wxWindow* pWindow = m_pBook->GetPage(page_idx);
			IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 
			if ( !pGS ) throw 1;
			
			wxString str = pGS->Save();
			wxFile file( dlg.GetPath(),  wxFile::write);
			file.Write( str );
		}
	}
	catch(...)
	{
		wxMessageBox(_("Failed!"), _("Error"), wxICON_WARNING | wxOK, this);
	}
}

void CMainWnd::OnSaveUI(wxUpdateUIEvent& event)
{
	try
	{
		if ( !m_pBook ) return;

		int page_idx = m_pBook->GetSelection();
		if (wxNOT_FOUND==page_idx) return;

		wxWindow* pWindow = m_pBook->GetPage(page_idx);
		IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 

		if ( pGS )
		{
			event.Enable( pGS->CanSave() );
		}
		else
		{
			event.Enable( false );
		}
	}catch(...)
	{
		event.Enable( false );
	}
}

void CMainWnd::OnClear(wxCommandEvent& event)
{
	try
	{
		if ( !m_pBook ) return;

		int page_idx = m_pBook->GetSelection();
		if (wxNOT_FOUND==page_idx) return;

		wxWindow* pWindow = m_pBook->GetPage(page_idx);
		IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 

		if ( !pGS ) throw 1;
			
		pGS->Clear();
	}
	catch(...)
	{
	}
}

void CMainWnd::OnClearUI(wxUpdateUIEvent& event)
{
	try
	{
		if ( !m_pBook ) return;

		int page_idx = m_pBook->GetSelection();
		if (wxNOT_FOUND==page_idx) return;

		wxWindow* pWindow = m_pBook->GetPage(page_idx);
		IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 

		if ( pGS )
		{
			event.Enable( pGS->CanClear() );
		}
		else
		{
			event.Enable( false );
		}
	}catch(...)
	{
		event.Enable( false );
	}
}

void CMainWnd::OnPanelClose(wxAuiManagerEvent& ev)
{
	if ( ev.GetPane()->window ==m_pHelpPanel  )
	{
		m_propStorage.SetShowHelpPanel(false);
	}
}

void CMainWnd::OnHelpPanel(wxCommandEvent& event)
{
	if ( m_pHelpPanel )
	{
		m_mgr.DetachPane(m_pHelpPanel);
		m_mgr.AddPane(m_pHelpPanel, wxRIGHT);
		m_mgr.Update();

		m_propStorage.SetShowHelpPanel();
	}
}

void CMainWnd::OnHelpPanelUI(wxUpdateUIEvent& event)
{
	if ( m_pHelpPanel )
	{
		event.Enable( !m_pHelpPanel->IsShown() );
	}
	else
		event.Enable(false);
}


void CMainWnd::OnQuit(wxCommandEvent& event)
{
	m_guilogic.PrepareToProgramExit();
	Close(true);
}

void CMainWnd::OnRefresh(wxCommandEvent& event)
{
	m_guilogic.Refresh();
}

void CMainWnd::OnUpdateSpeed(wxCommandEvent& event)
{
	time_t tUpd=10;

	switch( event.GetId() )
	{
		case ID_VIEW_UPD_SPEED_HIGH:
		{
			tUpd = HIGH_UPDATE_SPEED;
		}
		break;

		case ID_VIEW_UPD_SPEED_NORMAL:
		{
			tUpd = NORMAL_UPDATE_SPEED;
		}
		break;

		case ID_VIEW_UPD_SPEED_LOW:
		{
			tUpd = LOW_UPDATE_SPEED;
		}
		break;
	}

	m_guilogic.SetUpdateSpeed( tUpd );
	m_propStorage.SetUpdateSpeed( tUpd );
}

void CMainWnd::OnUpdateSpeedUpdateUI(wxUpdateUIEvent& event)
{
	time_t tUpd=m_guilogic.GetUpdateIntervl();


	switch( event.GetId() )
	{
		case ID_VIEW_UPD_SPEED_HIGH:
		{
			if ( HIGH_UPDATE_SPEED==tUpd )
			{
				event.Check(true);
			}
		}
		break;

		case ID_VIEW_UPD_SPEED_NORMAL:
		{
			if ( NORMAL_UPDATE_SPEED==tUpd )
			{
				event.Check(true);
			}
		}
		break;

		case ID_VIEW_UPD_SPEED_LOW:
		{
			if (LOW_UPDATE_SPEED==tUpd)
			{
				event.Check(true);
			}
		}
		break;
	}
}

void CMainWnd::OnViewLOG(wxCommandEvent& event)
{
	try
	{
		m_guilogic.ShowLogDlg();
	}catch(...)
	{

	}
}

void CMainWnd::OnViewLOGUpdateUI(wxUpdateUIEvent& event)
{
	event.Enable( !m_guilogic.IsLogWndShown() );
}

void CMainWnd::OnRestartRT(wxCommandEvent& event)
{
	int nRes = wxMessageBox(_("Are you sure?"), _("Question"),
				wxICON_QUESTION  | wxYES_NO, this);

	if ( wxYES==nRes )
	{
		m_guilogic.DoRouterReboot( _("Router rebooted by User.") );
	}
}

void CMainWnd::OnRestartRTUI(wxUpdateUIEvent& event)
{
	event.Enable( m_guilogic.IsConnected() ); 
}

void CMainWnd::OnConWizard(wxCommandEvent& event)
{
	ShowConnectionWizard();
}

void CMainWnd::OnOptions(wxCommandEvent& event)
{
	ShowConfig();
}

void CMainWnd::OnUpdateCheck(wxCommandEvent& event)
{
	DoUpdateCheck();
}

void CMainWnd::OnHelpTranslate(wxCommandEvent& event)
{
	wxString strURL=wxT("http://www.routercommander.com/help/howto#translate");
	wxLaunchDefaultBrowser(strURL);
}

void CMainWnd::OnHelp(wxCommandEvent& event)
{
	wxString strURL=wxT("http://routercommander.com/index.php?option=com_content&view=article&id=4&Itemid=4");
	wxLaunchDefaultBrowser(strURL);
}

void CMainWnd::OnAbout(wxCommandEvent& event)
{
	wxAboutDialogInfo info;

	info.SetName(_("Router Commander"));

	info.SetVersion(PROG_VERSION);
	info.SetDescription(_("Router Commander"));
	info.SetCopyright(wxT("(C) 2009-2011 Home Network Soft"));
	info.AddDeveloper(wxT("Ryuho"));
	info.SetWebSite(wxT("www.routercommander.com"));

	wxAboutBox(info);
}

//////////////////////////////////////////////////////////////////////////////////////////
//Custom
void CMainWnd::OnProcessThreadExit(wxCommandEvent& event)
{
	OutputDebugStr(_("CMainWnd::OnProcessThreadExit() Begin()\n"));
	m_guilogic.DestroyLinkToRouter( event.GetId() );

	if (m_pHelpPanel)
	{
		m_pHelpPanel->ShowErr( event.GetId() );
	}

	OutputDebugStr(_("CMainWnd::OnProcessThreadExit() End()\n"));
}

void CMainWnd::OnProcessRouterData(wxCommandEvent& event)
{
	if ( !m_bInside )
	{
		CRecursvGuard guard( m_bInside  );
		m_guilogic.ProcessCmd();
	}
}

void CMainWnd::OnNewLogMsg(wxCommandEvent& event)
{
	wxCriticalSectionLocker locker(m_critical);
	
	m_guilogic.ProcessSysLogCmd();
}

//////////////////////////////////////////////////////////////////////////////////////////
//PopUP
void CMainWnd::OnConfig(wxCommandEvent& event)
{
	ShowConfig(m_plCurType);
}

void CMainWnd::OnRefreshOne(wxCommandEvent& event)
{
	m_guilogic.Refresh(m_plCurType);
}

//////////////////////////////////////////////////////////////////////////////////////////
//Events
void CMainWnd::OnIconize(wxIconizeEvent& event)
{
	if ( event.Iconized() )
	{
		Show(false);
	}
}

void CMainWnd::SetPrgTitle(const wxString& str)
{
	wxString strTitle = m_strTitle;
	strTitle+=wxT("[");
	strTitle+=str;
	strTitle+=wxT("]");

	SetTitle(strTitle);
}

//<routercmd version="1.0.10">
//	<win>http://www.routercommander.com/download/rtcmdsetup.exe</win>
//</routercmd>
//check for updates option
//check latest PROG_VERSION
void CMainWnd::DoUpdateCheck(bool bSilent)
{
	wxHTTP get;
	get.SetHeader(_("Content-type"), _("text/html; charset=utf-8"));
	get.SetTimeout(10);
	 
	// this will wait until the user connects to the internet. It is important in case of dialup (or ADSL) connections
	int nRet=3;
	while (nRet-->0 && !get.Connect(_("www.routercommander.com")))
		wxSleep(1);

	wxString strURL=_("/download/rtcversion.xml?");

	strURL+=wxT("v=");
	strURL+=PROG_VERSION;
	
	#ifdef LINUX
	strURL+=wxT(",p=L");
	#endif

	wxInputStream *httpStream = get.GetInputStream(strURL);

	if (get.GetError() == wxPROTO_NOERR)
	{
		wxString res;
		wxStringOutputStream out_stream(&res);
		httpStream->Read(out_stream);

		CMarkupSTL	doc;

		if ( doc.SetDoc(res.ToAscii()) &&
			 doc.FindElem("routercmd") )
		{
			std::string strVer = doc.GetAttrib("version");
			std::string strPath;

			#ifdef WIN32
			if ( doc.FindChildElem("win") )
			{
				strPath = doc.GetChildData();
				std::string strVer2 = doc.GetChildAttrib("version");
				strVer = strVer2.empty()?strVer:strVer2;
			}
			#elif LINUX
			if ( doc.FindChildElem("linux") )
			{
				strPath = doc.GetChildData();
				std::string strVer2 = doc.GetChildAttrib("version");
				strVer = strVer2.empty()?strVer:strVer2;
			}
			#else
			if ( doc.FindChildElem("mac") )
			{
				strPath = doc.GetChildData();
				std::string strVer2 = doc.GetChildAttrib("version");
				strVer = strVer2.empty()?strVer:strVer2;
			}
			#endif

			if ( !strVer.empty() && !strPath.empty() )
			{
				wxString wxstrVer = wxString::FromAscii(strVer.c_str());

				if ( IsVersionChanged(strVer) )
				{
					Show();

					CUpdateDlg dlg(wxstrVer,
						wxString::FromAscii(strPath.c_str()));

					dlg.ShowModal();
				}
				else
				{
					if (!bSilent) wxMessageBox( _("You have the latest version.") );
				}
			}
		}
	}
	else
		if (!bSilent) wxMessageBox( _("Unable to connect to update server") );
 
	wxDELETE(httpStream);
	get.Close();
}

bool CMainWnd::IsVersionChanged(const std::string& strVer )
{
	unsigned int vI1(0), vI2(0), vI3(0);
	unsigned int v1(0),  v2(0),  v3(0);

	sscanf(strVer.c_str(), "%u.%u.%u", &vI1, &vI2, &vI3);

	wxString strCur(PROG_VERSION);
	wxSscanf(strCur, wxT("%u.%u.%u"), &v1, &v2, &v3);

	if ( vI1>v1 ) return true;
	else
	if ( vI1<v1 ) return false;

	if ( vI2>v2 ) return true;
	else
	if ( vI2<v2 ) return false;

	if ( vI3>v3 ) return true;

	return false;
}

void CMainWnd::OnHelpPressed(wxHelpEvent& event)
{
	wxGetApp().RunHelp( wxT("") );
}

void CMainWnd::OnOptimizationSelector(wxCommandEvent& event)
{
	GetPropStorage().SetEnableP2PNetworkOpt(false);
	GetPropStorage().SetEnableWWWOpt(false);
	GetPropStorage().SetEnableAdvancedOpt(false);

	switch( event.GetId() )
	{
		case ID_TOOLS_P2P_OPT:
		{
			GetPropStorage().SetEnableP2PNetworkOpt();
		}
		break;

		case ID_TOOLS_WWW_OPT:
		{
			 GetPropStorage().SetEnableWWWOpt();
		}
		break;

		case ID_TOOLS_CUSTOM_OPT:
		{
			STRINGPAIRLIST lst = GetPropStorage().GetAdvancedOptList();
			if ( lst.empty() )
			{
				CAdvancedOptDlg dlg(this);
				dlg.Load( lst );

				if ( dlg.ShowModal() == wxID_OK )
				{
					lst = dlg.Save();

					GetPropStorage().SetAdvancedOptList(lst);
					GetPropStorage().SetEnableAdvancedOpt();
				}
			}
			else
			{
				GetPropStorage().SetEnableAdvancedOpt();
			}
		}
		break;
	}

	GetPropStorage().Save();
	GetLogic().DoStartUpAction();
	GetLogic().Refresh();
}

void CMainWnd::OnOptimizationSelectorUI(wxUpdateUIEvent& event)
{
	bool bEnabled;

	switch( event.GetId() )
	{
		case ID_TOOLS_P2P_OPT:
		{
			bEnabled = GetPropStorage().GetEnableP2PNetworkOpt();
			event.Check(bEnabled);
		}
		break;

		case ID_TOOLS_WWW_OPT:
		{
			bEnabled = GetPropStorage().GetEnableWWWOpt();
			event.Check(bEnabled);
		}
		break;

		case ID_TOOLS_CUSTOM_OPT:
		{
			bEnabled = GetPropStorage().GetEnableAdvancedOpt();
			event.Check(bEnabled);
		}
		break;
	}
}

void CMainWnd::OnAdvanced(wxCommandEvent& ev)
{
	int page_idx = m_pBook->GetSelection();
	if ( wxNOT_FOUND!=page_idx )
	{
		wxWindow* pWindow = m_pBook->GetPage(page_idx);

		if ( pWindow )
		{
			IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 

			if ( pGS )
			{
				pGS->ShowAdvanced( ev.IsChecked() );
			}
		}
	}
}

void CMainWnd::OnAdvancedUpdateUI(wxUpdateUIEvent& event)
{
	bool bEnable(false);

	if (!m_pBook) return;

	int page_idx = m_pBook->GetSelection();
	if ( wxNOT_FOUND!=page_idx )
	{
		wxWindow* pWindow = m_pBook->GetPage(page_idx);

		if ( pWindow )
		{
			IGUISupport* pGS = dynamic_cast<IGUISupport*>(pWindow); 

			if ( pGS )
			{
				bEnable = pGS->CanShowAdvanced();
				event.Check( pGS->IsAdvancedShown() );
			}
		}
	}

	event.Enable( bEnable );
}

void CMainWnd::GenerateStatusLog()
{
	for ( size_t i=0;i<m_pBook->GetPageCount();++i)
	{
		try
		{
			wxWindow* wnd = m_pBook->GetPage(i);
			ILoggable* pLog = dynamic_cast<ILoggable*>(wnd);

			if ( pLog )
			{
				wxString strRecord = pLog->GetLog();

				if ( !strRecord.empty() )
				{
					LOGENTRY entry;
					entry.bStatus = true;
					entry.strCustomEvent = strRecord;
					m_guilogic.AddToLog( entry );
				}
			}
		}
		catch (...)
		{
		}
	}
}

void CMainWnd::OnDonation(wxCommandEvent& event)
{
	wxString strURL=wxT("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=thankyou%40routercommander%2ecom&lc=GB&item_name=Support%20Router%20Commander%20development&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG_global%2egif%3aNonHosted");
	wxLaunchDefaultBrowser(strURL);
}

void CMainWnd::OnCompatibReport(wxCommandEvent& event)
{
	try
	{
		CReportWindow wnd(this, m_config.GetUser());
		wnd.ShowModal();
	}catch(...) {}

}

void CMainWnd::OnCompatibReportUI(wxUpdateUIEvent& event)
{
	event.Enable( !CRouterCaps::GetIntstance().GetShellName().empty()  );
}


void CMainWnd::OnTimeSelector(wxCommandEvent& event)
{
	int page_idx = m_pBook->GetSelection();

	if ( wxNOT_FOUND!=page_idx )
	{
		wxWindow* pWindow = m_pBook->GetPage(page_idx);

		if ( pWindow )
		{
			ITabedPageUI* pGS = dynamic_cast<ITabedPageUI*>(pWindow); 

			if ( pGS )
			{
				for (size_t i=0;i<sizeof(gPerTable)/sizeof(gPerTable[0]);++i)
				{
					if ( gPerTable[i].iID == event.GetId() )
					{
						pGS->SetTimeInterval( gPerTable[i].iVAL );
						break;
					}
				}
			}
		}
	}
}

void CMainWnd::OnTimeSelectorUI(wxUpdateUIEvent& event)
{
	bool bEnable(false);

	int page_idx = m_pBook->GetSelection();
	if ( wxNOT_FOUND!=page_idx )
	{
		wxWindow* pWindow = m_pBook->GetPage(page_idx);

		if ( pWindow )
		{
			ITabedPageUI* pGS = dynamic_cast<ITabedPageUI*>(pWindow); 

			if ( pGS )
			{
				bEnable = pGS->IsTimeSelectorSupported();

				size_t tCur = pGS->GetTimeInterval();

				for (size_t i=0;i<sizeof(gPerTable)/sizeof(gPerTable[0]);++i)
				{
					if ( gPerTable[i].iID  == event.GetId() &&
						 gPerTable[i].iVAL == tCur )
					{
						event.Check(true);
					}
				}
			}
		}
	}

	event.Enable( bEnable );
}
